/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.iaroc.gui;


import java.awt.Graphics;
import java.util.Hashtable;
import javax.swing.JFrame;
import javax.swing.JLabel;
import com.grt192.core.Sensor;
import com.grt192.event.SensorChangeListener;
import com.grt192.event.SensorEvent;

/**
 *
 * @author gerberduffy
 */
public class IarocDashboard extends JFrame implements SensorChangeListener{
    
    private Hashtable sensorLabels;
    
    /*
     * Default constructor
     */
    public IarocDashboard(){
        sensorLabels = new Hashtable();
    }
    
    /*
     * @return The current Graphics Context object
     */
    public Graphics getCurrentGraphics(){
        return getContentPane().getGraphics();
    }

    /*
     * Add a sensor-label pair to the Hashtable
     */
    public void addSensorLabel(Sensor s, String label){
        JLabel l = new JLabel(label);
        
        s.addSensorChangeListener(this);
        
        String sensorSource = s.getId();
        
        sensorLabels.put(sensorSource, l);
        
        getContentPane().add(l);
        l.setVisible(true);
    }
    
    public void updateLabel(Sensor s, String newText){
        
        String sensorName = s.getId();
        
        if ( sensorLabels.containsKey(sensorName) ){
            ((JLabel)sensorLabels.get(sensorName)).setText(newText);
        }
    }
    
    /*
     * From a SensorEvent, create a properly formatted String that 
     * can be added to the Frame.
     */
    public String getFormattedLabelFromSensorEvent(SensorEvent e, String key){
        String source = e.getSource().getId();
        double value = e.getSource().getState(key);
        
        String labelText = source + " : " + value;
        
        return labelText;
    }
    
    /*
     * Called when the Sensor updates its state. 
     * Updates the Label if it exists already.
     */
    public void sensorStateChanged(SensorEvent e, String key) {
        Sensor source = e.getSource();
        
        if (sensorLabels.containsKey(source.getId())){
            updateLabel(source, getFormattedLabelFromSensorEvent(e, key));
        }
    }    
}
